<?php


namespace app\service;


use app\dao\UsingRoomTimeDao;
use app\lib\exception\ServiceException;
use app\utils\DateTime;
use think\Exception;
use think\facade\Db;

class UsingRoomTimeService
{
    private $UsingRoomTimeDao;
    private $Convert;

    public function __construct()
    {
        $this->Convert = new DateTime();
        $this->UsingRoomTimeDao = new UsingRoomTimeDao();
    }

    public function getUsingRoomTime($id){
        return $this->UsingRoomTimeDao->customQuery()->fieldById($id)->withRoom()->getOne();
    }

    public function getUsingRoomTimeList($page , $limit){
        return $this->UsingRoomTimeDao->customQuery()->orderByRoomId()->withRoom()->getList($page , $limit);
    }

    public function getUsingRoomTimeByRoomId($room_id){
        return $this->UsingRoomTimeDao->customQuery()->fieldByRoomId($room_id)->getAll();
    }

    public function editUsingRoomTime($id , $data){
        $editData = [];
        empty($data['room_id']) || $editData['room_id'] = $data['room_id'];
        empty($data['start_time']) || $editData['start_time'] = $this->Convert->setTime($data['start_time']);
        empty($data['end_time']) || $editData['end_time'] = $this->Convert->setTime($data['end_time']);

        try {
            Db::startTrans();
            $this->UsingRoomTimeDao->edit($id , $editData);
            $result = $this->getUsingRoomTime($id);
            if (!empty($data['start_time'] || !empty($data['end_time'])))
                $result = $this->UsingRoomTimeDao->edit($id , ['day' => $this->Convert->getDay($result->start_time , $result->end_time)]);
            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
            throw new ServiceException($exception->getMessage());
        }
        return $result;
    }

    public function delUsingRoomTime($id){
        $this->UsingRoomTimeDao->delete($id);
    }

    public function addUsingRoomTime($room_id  , $start_time , $end_time){
        return $this->UsingRoomTimeDao->save([
            'room_id' => $room_id,
            'day' => '',
            'start_time' => $start_time,
            'end_time' => $end_time,
        ]);
    }
}